package net.soevar.action.admins;

import java.util.List;

import net.soevar.common.Common;
import net.soevar.common.CommonPrivilages;
import net.soevar.common.DesEncrypter;
import net.soevar.database.dao.AthUserDao;
import net.soevar.database.dao.DaoFactory;
import net.soevar.database.hibernate.HibernateUtil;
import net.soevar.database.model.AthRole;
import net.soevar.database.model.AthUser;

import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.util.GenericAutowireComposer;
import org.zkoss.zul.Borderlayout;
import org.zkoss.zul.Caption;
import org.zkoss.zul.Center;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Combobox;
import org.zkoss.zul.Grid;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Label;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Row;
import org.zkoss.zul.RowRenderer;
import org.zkoss.zul.Rows;
import org.zkoss.zul.SimpleListModel;
import org.zkoss.zul.South;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Toolbar;
import org.zkoss.zul.Toolbarbutton;
import org.zkoss.zul.Window;

public class UserAction extends GenericAutowireComposer {
	private static final long serialVersionUID = -4773866524211953179L;
	private Window addWindow;
	private Grid grid;

	private Textbox searchnama;
	private Textbox userNama;
	private Textbox userid;
	private Textbox userPassword;
	private Combobox userRole;
	private Checkbox userRoot;
	private Checkbox userAktif;
	private Checkbox userApproval;

	private Combobox searchrole;

	private boolean edit;
	private boolean delete;

	private AthUser athuser;
	private Toolbarbutton add;

	private DesEncrypter desEncrypter = new DesEncrypter(Common.DES_PASS_PHRASE);

	@Override
	public void doAfterCompose(Component comp) throws Exception {
		// TODO Auto-generated method stub
		super.doAfterCompose(comp);

		AthUser athuser = Common.getCurrentUser();

		if (session.getAttribute("usersTemp") == null
				|| !CommonPrivilages.checkPrevilages(CommonPrivilages.READ)
				|| athuser.getStatusRoot() == null || !athuser.getStatusRoot()

		) {
			session.removeAttribute("usersTemp");
			execution.sendRedirect("/logoff");
			return;
		}

		add.setVisible(CommonPrivilages
				.checkPrevilages(CommonPrivilages.CREATE));
		add.setTooltiptext("Tambah");

		edit = CommonPrivilages.checkPrevilages(CommonPrivilages.UPDATE);
		delete = CommonPrivilages.checkPrevilages(CommonPrivilages.DELETE);

		Common.insertCombo(searchrole, "roleName", AthRole.class);
		Common.insertCombo(userRole = new Combobox(), "roleName", AthRole.class);

		// if
		// (Common.getCurrentUser().getUserRole().getRoleId().equals("admin")) {
		// Common.insertCombo(userRole = new Combobox(), "roleName",
		// AthRole.class, Restrictions.ne("roleId", "admin"));
		// Common.insertCombo(searchrole, "roleName", AthRole.class);
		// } else {
		// Common.insertCombo(userRole = new Combobox(), "roleName",
		// AthRole.class, Restrictions.eq("roleId", "Dosen"));
		// Common.insertCombo(searchrole, "roleName", AthRole.class,
		// Restrictions.ne("roleId", "am"));
		// }

		onSearchDefault(null);
	}

	class UserRenderer implements RowRenderer {

		@Override
		public void render(final Row arg0, Object arg1) throws Exception {
			// TODO Auto-generated method stub
			final AthUser athuser = (AthUser) arg1;

			new Label(athuser.getUserNama()).setParent(arg0);
			new Label(athuser.getUserRole().getRoleName()).setParent(arg0);
			new Label(athuser.getStatusAktif() == null ? "" : athuser
					.getStatusAktif().toString()).setParent(arg0);
			new Label(athuser.getStatusApproval() == null ? "" : athuser
					.getStatusApproval().toString()).setParent(arg0);
			new Label(athuser.getStatusRoot() == null ? "" : athuser
					.getStatusRoot().toString()).setParent(arg0);

			Hbox toolbar = new Hbox();
			Toolbarbutton button = new Toolbarbutton("",
					"/include/img/icon-edit.png");
			button.setTooltiptext("Rubah Data");
			button.setVisible(edit);
			button.addEventListener("onClick", new EventListener() {
				@Override
				public void onEvent(Event event) throws Exception {
					init(athuser);
					addWindow.setVisible(true);
					addWindow.onModal();
				}

			});
			button.setParent(toolbar);

			button = new Toolbarbutton("", "/include/img/icon-delete.png");
			button.setTooltiptext("Hapus Data");
			button.setVisible(delete);
			button.addEventListener("onClick", new EventListener() {
				@Override
				public void onEvent(Event event) throws Exception {
					Messagebox.show("Apakah yakin ingin menghapus data ini ?",
							"Question", Messagebox.OK | Messagebox.CANCEL,
							Messagebox.QUESTION, new EventListener() {

								@Override
								public void onEvent(Event event)
										throws Exception {
									int i = new Integer(event.getData()
											.toString());
									if (i == Messagebox.OK) {
										try {
											AthUserDao athuserDao = DaoFactory
													.getInstance()
													.getAthUserDao();
											// agamaDao.beginTransaction();
											athuserDao.delete(athuserDao
													.merge(athuser));
											// agamaDao.commitTransaction();
											arg0.detach();
										} catch (Exception e) {
											e.printStackTrace();
											Messagebox
													.show("Data ini tidak dapat dihapus ..");
										}

									}

								}
							});

				}
			});
			button.setParent(toolbar);
			toolbar.setParent(arg0);
		}

	}

	public void onAdd(Event event) throws Exception {
		init(new AthUser());
		addWindow.setVisible(true);
		addWindow.onModal();
	}

	private void init(AthUser athuser) {
		this.athuser = athuser;
		addWindow.setTitle("Pendataan User");
		Common.clear(addWindow);
		Borderlayout borderlayout = new Borderlayout();
		Center center = new Center();
		center.setParent(borderlayout);
		center.setFlex(true);
		Grid grid = new Grid();
		grid.setParent(center);
		grid.setWidth("100%");
		grid.setHeight("100%");
		grid.setOddRowSclass("non-odd");

		Rows rows = new Rows();
		rows.setParent(grid);

		Row row = new Row();
		row.setStyle("border:0px;background: transparent;");
		row.setParent(rows);
		row.appendChild(new Label("User id"));
		row.appendChild(userid = new Textbox(athuser.getUserId() == null ? ""
				: athuser.getUserId()));
		userid.setCols(40);

		row = new Row();
		row.setStyle("border:0px;background: transparent;");
		row.setParent(rows);
		row.appendChild(new Label("Nama"));
		row.appendChild(userNama = new Textbox(
				athuser.getUserNama() == null ? "" : athuser.getUserNama()));
		userNama.setCols(40);

		row = new Row();
		row.setStyle("border:0px;background: transparent;");
		row.setParent(rows);
		row.appendChild(new Label("Password"));
		row.appendChild(userPassword = new Textbox(
				athuser.getUserPassword() == null ? "" : athuser
						.getUserPassword()));

		if (athuser.getIsEncripted() != null && athuser.getIsEncripted()) {
			try {
				userPassword.setValue(athuser.getUserPassword() == null ? ""
						: desEncrypter.decrypt(athuser.getUserPassword()));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		userPassword.setType("password");
		userPassword.setCols(40);

		// row = new Row();
		// row.setStyle("border:0px;background: transparent;");
		// row.setParent(rows);
		// row.appendChild(new Label("Ter-enkrpsi"));
		// row.appendChild(isEncripted = new Checkbox());
		// isEncripted.setChecked(tbmuser.getIs_encripted() != null
		// && tbmuser.getIs_encripted());

		row = new Row();
		row.setStyle("border:0px;background: transparent;");
		row.setParent(rows);
		row.appendChild(new Label("Role"));
		// List<AthRole> athroles = HibernateUtil.currentSession()
		// .createCriteria(AthRole.class).list();
		// Common.insertComboItems(userRole, "roleName", athroles);
		Common.selectComboItem(userRole, athuser.getUserRole() == null ? null
				: athuser.getUserRole());
		row.appendChild(userRole);
		userRole.setCols(40);

		row = new Row();
		row.setStyle("border:0px;background: transparent;");
		row.setParent(rows);
		row.appendChild(new Label("Status Aktif"));
		row.appendChild(userAktif = new Checkbox());
		userAktif.setChecked(athuser.getStatusAktif() == null ? false : athuser
				.getStatusAktif().equals(1));
		userAktif.addEventListener("onCheck", new EventListener() {
			@Override
			public void onEvent(Event arg0) throws Exception {
				if (userAktif.isChecked()) {
					userAktif.setAttribute("myValue", 1);
				} else {
					userAktif.setAttribute("myValue", 0);
				}
			}
		});

		row = new Row();
		row.setStyle("border:0px;background: transparent;");
		row.setParent(rows);
		row.appendChild(new Label("Status Approval"));
		row.appendChild(userApproval = new Checkbox());
		userApproval.setChecked(athuser.getStatusApproval() == null ? false
				: athuser.getStatusApproval().equals(1));
		userApproval.addEventListener("onCheck", new EventListener() {
			@Override
			public void onEvent(Event arg0) throws Exception {
				if (userApproval.isChecked()) {
					userApproval.setAttribute("myValue", 1);
				} else {
					userApproval.setAttribute("myValue", 0);
				}
			}
		});

		row = new Row();
		row.setStyle("border:0px;background: transparent;");
		row.setParent(rows);
		row.appendChild(new Label("Status Root"));
		row.appendChild(userRoot = new Checkbox());
		userRoot.setChecked(athuser.getStatusRoot() == null ? false : athuser
				.getStatusRoot().equals(1));
		userRoot.addEventListener("onCheck", new EventListener() {
			@Override
			public void onEvent(Event arg0) throws Exception {
				if (userRoot.isChecked()) {
					userRoot.setAttribute("myValue", 1);
				} else {
					userRoot.setAttribute("myValue", 0);
				}
			}
		});

		South south = new South();
		south.setFlex(true);
		south.setParent(borderlayout);

		Toolbar toolbar = new Toolbar();
		toolbar.setParent(south);
		Toolbarbutton cancel = new Toolbarbutton("Batal",
				"/include/img/icon-back.png");
		cancel.setTooltiptext("Tutup");
		cancel.addEventListener("onClick", new EventListener() {
			@Override
			public void onEvent(Event event) throws Exception {
				addWindow.setVisible(false);
			}
		});
		cancel.setParent(toolbar);
		Toolbarbutton save = new Toolbarbutton("Simpan",
				"/include/img/icon-save.png");
		save.setTooltiptext("Simpan");
		save.addEventListener("onClick", new EventListener() {
			@Override
			public void onEvent(Event event) throws Exception {
				if (onSave(event)) {
					onSearchDefault(null);
					addWindow.setVisible(false);
				}
			}
		});
		save.setParent(toolbar);
		borderlayout.setParent(addWindow);
		Caption caption = new Caption();
		Toolbarbutton button = new Toolbarbutton(" X ");
		button.addEventListener("onClick", new EventListener() {
			@Override
			public void onEvent(Event event) throws Exception {
				addWindow.setVisible(false);
			}

		});
		button.setParent(caption);
		// caption.setParent(addWindow);
	}

	public boolean onSave(Event event) throws Exception {
		if (userNama.getValue().trim().equals("")) {
			Messagebox.show("Username harus diisi", "Peringatan", 1,
					Messagebox.INFORMATION);
			return false;
		}
		if (userPassword.getValue().trim().equals("")) {
			Messagebox.show("Password harus diisi", "Peringatan", 1,
					Messagebox.INFORMATION);
			return false;
		}
		if (userRole.getSelectedItem() == null) {
			Messagebox.show("Role harus dipilih", "Peringatan", 1,
					Messagebox.INFORMATION);
			return false;
		}

		boolean i = checkUser();
		if (i) {
			Messagebox
					.show("Username sudah terpakai,silahkan pilih username yang lain",
							"Peringatan", 1, Messagebox.INFORMATION);
			return false;
		}

		AthUserDao athuserDao = DaoFactory.getInstance().getAthUserDao();
		if (athuser.getUserId() != null) {
			athuser = athuserDao.load(athuser.getUserId());

		}

		athuser.setUserId(userid.getValue());
		athuser.setUserNama(userNama.getValue());
		athuser.setUserPassword(desEncrypter.encrypt(userPassword.getValue()));
		athuser.setIsEncripted(true);
		athuser.setUserRole((AthRole) userRole.getSelectedItem().getValue());
		athuser.setStatusAktif(userAktif.isChecked() ? true : false);
		athuser.setStatusApproval(userApproval.isChecked() ? true : false);
		athuser.setStatusRoot(userRoot.isChecked() ? true : false);

		if (athuser.getUserId() != null) {
			athuserDao.update(athuser);
		} else {
			athuserDao.save(athuser);
		}

		return true;
	}

	@SuppressWarnings("unchecked")
	public void onSearchDefault(Event event) {
		Session session = HibernateUtil.currentSession();
		List<AthUser> athuser = session
				.createCriteria(AthUser.class)
				.addOrder(Order.asc("userNama"))
				.add(Restrictions.ilike("userNama", searchnama.getValue()
						.trim(), MatchMode.ANYWHERE))
				.add(searchrole.getSelectedItem() == null ? Restrictions
						.sqlRestriction("1=1") : Restrictions.eq("userRole",
						searchrole.getSelectedItem().getValue()))
				// .add(Restrictions.eq("userShow", 1))
				.setMaxResults(Common.MAX_RESULT).list();
		ListModel strset = new SimpleListModel(athuser);
		grid.setRowRenderer(new UserRenderer());
		grid.setModel(strset);

		grid.renderAll();
		grid.setOddRowSclass("non-odd");

	}

	public Boolean checkUser() {

		Integer userCount = null;
		Session session = HibernateUtil.currentSession();
		userCount = ((Number) session
				.createCriteria(AthUser.class)
				.setProjection(Projections.count("id"))
				.add(Restrictions.eq("userId", userid.getValue().trim()))
				.add(this.athuser.getUserId() == null ? Restrictions
						.sqlRestriction("1=1") : Restrictions.ne("id",
						this.athuser.getUserId())).uniqueResult()).intValue();

		return !userCount.equals(0);
	}
}
